<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    title="绑定邮箱"
    width="500px"
    destroy-on-close
  >
    <el-form 
      :model="emailBindForm" 
      :rules="emailRules" 
      ref="emailBindFormRef" 
      label-width="100px"
    >
      <el-form-item label="邮箱地址" prop="email">
        <el-input 
          v-model="emailBindForm.email" 
          placeholder="请输入邮箱地址"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="验证码" prop="verificationCode">
        <div class="code-input-group">
          <el-input 
            v-model="emailBindForm.verificationCode" 
            placeholder="请输入6位数字验证码"
            maxlength="6"
            style="flex: 1; margin-right: 10px;"
          ></el-input>
          <el-button 
            @click="sendEmailCode" 
            :loading="emailCodeSending"
            :disabled="emailCodeCountdown > 0"
          >
            {{ emailCodeCountdown > 0 ? `${emailCodeCountdown}s` : '发送验证码' }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm" 
          :loading="loading"
        >
          确认绑定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { sendEmailVerificationCode } from '@/api/security';

// Props和Events定义
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'confirm']);

// 响应式数据
const emailBindFormRef = ref(null);
const loading = ref(false);
const emailCodeSending = ref(false);
const emailCodeCountdown = ref(0);
const emailBindForm = reactive({
  email: '',
  verificationCode: ''
});

// 邮箱验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
};

// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!emailBindForm.email) {
    ElMessage.error('请先输入邮箱地址');
    return;
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!emailRegex.test(emailBindForm.email)) {
    ElMessage.error('请输入正确的邮箱地址');
    return;
  }
  
  try {
    emailCodeSending.value = true;
    
    await sendEmailVerificationCode(emailBindForm.email, 'bind');
    
    ElMessage.success('验证码已发送到邮箱');
    
    // 开始倒计时
    emailCodeCountdown.value = 60;
    const timer = setInterval(() => {
      emailCodeCountdown.value--;
      if (emailCodeCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error) {
    console.error('发送验证码失败:', error);
    ElMessage.error('发送验证码失败，请重试');
  } finally {
    emailCodeSending.value = false;
  }
};

// 重置表单
const resetForm = () => {
  emailBindForm.email = '';
  emailBindForm.verificationCode = '';
  emailCodeCountdown.value = 0;
  if (emailBindFormRef.value) {
    emailBindFormRef.value.resetFields();
  }
};

// 确认绑定
const handleConfirm = async () => {
  if (!emailBindFormRef.value) return;
  
  await emailBindFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await emit('confirm', { ...emailBindForm });
        resetForm();
      } finally {
        loading.value = false;
      }
    }
  });
};

// 监听对话框关闭，重置表单
watch(() => props.modelValue, (newValue) => {
  if (!newValue) {
    resetForm();
  }
});
</script>

<style scoped>
.code-input-group {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .code-input-group {
    flex-direction: column;
    gap: 10px;
  }
  
  .code-input-group .el-input {
    margin-right: 0 !important;
  }
}
</style>
